package com.cw.controller;

import com.cw.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Nice_BernardShaw
 * @date 2022/9/3 0:15
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    /**
     * @param file  文件上传
     * @return
     */
    @Value("${campusWm.imgDir}")
    private String imgDir;
    @PostMapping("/upload")
    public R upload(MultipartFile file)  {
        String fileName= UUID.randomUUID().toString();
        File url = new File(imgDir);
        if (!url.exists()){
            url.mkdirs();
        }
        try {
            file.transferTo(new File(url,fileName));
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("文件上传失败");
        }
        log.info(file.toString());
        return R.success(fileName);
    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(new File(imgDir, name));
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("image/jpeg");
        IOUtils.copy(fileInputStream,outputStream);
        fileInputStream.close();
    }
}
